package com.csu.mall.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csu.mall.common.Global;
import com.csu.mall.common.utils.PageUtils;
import com.csu.mall.common.utils.Query;
import com.csu.mall.common.utils.R;
import com.csu.mall.ware.dao.PurchaseDao;
import com.csu.mall.ware.dao.PurchaseDetailDao;
import com.csu.mall.ware.dao.WareSkuDao;
import com.csu.mall.ware.dto.SkuInfoVo;
import com.csu.mall.ware.entity.PurchaseDetailEntity;
import com.csu.mall.ware.entity.PurchaseEntity;
import com.csu.mall.ware.entity.WareSkuEntity;
import com.csu.mall.ware.feign.GatewayFeignService;
import com.csu.mall.ware.service.PurchaseDetailService;
import com.csu.mall.ware.service.PurchaseService;
import com.csu.mall.ware.vo.ItemVo;
import com.csu.mall.ware.vo.PurchaseDetailVo;
import com.csu.mall.ware.vo.PurchaseVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
    @Resource
    private PurchaseDetailService purchaseDetailService;

    @Resource
    private PurchaseDetailDao purchaseDetailDao;

    @Resource
    private PurchaseDao purchaseDao;

    @Resource
    private WareSkuDao wareSkuDao;

    @Resource
    private GatewayFeignService gatewayFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage() {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        wrapper.lt("status", Global.WareConstant.OrderStatus.FINISHED.getCode());
        IPage<PurchaseEntity> page = this.page(
                new Page<PurchaseEntity>(),
                wrapper
        );
        return new PageUtils(page);
    }

    @Override
    public void mergePurchaseDetail(PurchaseDetailVo purchaseDetailVo) {
        Long purchaseId = purchaseDetailVo.getPurchaseId();
        PurchaseEntity purchase = null;
        if(purchaseId == null){
            purchase = new PurchaseEntity();
            this.save(purchase);
            purchaseId = purchase.getId();
        }
        if(purchase == null){
            purchase = this.getById(purchaseId);
        }
        //判断采购单状态，只有状态是新建或者已分配，才可以合并采购需求,否则，合并失败
        //TODO 这种情况，应该向上返回异常，告知前端
        if(purchase.getStatus() >= Global.WareConstant.OrderStatus.PICKED.getCode()) return;


        List<Long> items = purchaseDetailVo.getItems();
        List<PurchaseDetailEntity> purchaseDetailEntities = null;
        if(items != null && items.size() > 0){
            purchaseDetailEntities = new ArrayList<>();
            for(Long item: items){
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setPurchaseId(purchaseId);
                purchaseDetailEntity.setId(item);
                purchaseDetailEntities.add(purchaseDetailEntity);
            }
            purchaseDetailService.updateBatchById(purchaseDetailEntities);

            purchase.setId(purchaseId);
            purchase.setUpdateTime(new Date());
            this.updateById(purchase);
        }

    }

    @Transactional
    @Override
    public void receivedPurchase(List<Long> purchaseIds) {
        //领取订单的时候，只有新建状态或者已分配的订单 才能领取
        List<PurchaseEntity> purchaseEntities = purchaseDao.batchSelectEntity(purchaseIds);
        List<PurchaseEntity> collect = purchaseEntities.stream().
                filter(item->{
                    return item.getStatus() == Global.WareConstant.OrderStatus.NEW_STATUS.getCode() ||
                            item.getStatus() == Global.WareConstant.OrderStatus.ALLOWCATED.getCode();
                }).collect(Collectors.toList());
        if(collect.size() <= 0) return;

        //1.改变订单状态
        collect.forEach(item->{
            item.setStatus(Global.WareConstant.OrderStatus.PICKED.getCode());
        });
        this.updateBatchById(collect);

        //2.改变订单的采购项（采购需求）的状态
        List<Long> purchaseIDs = collect.stream().map(PurchaseEntity::getId).collect(Collectors.toList());
        purchaseDetailDao.updateBatchByPurchaseId(purchaseIDs);

    }

    @Transactional
    @Override
    public void donePurchase(PurchaseVo purchaseVo) {
        List<ItemVo> items = purchaseVo.getItems();//拿到订单下采购项的的items
//        List<Long> itemId = items.stream().map(ItemVo::getItemId).collect(Collectors.toList());
//        List<PurchaseDetailEntity> purchaseDetailEntityList = purchaseDetailDao.selectBatchIds(itemId);
        //1.拿到采购成功的采购项ID
        boolean done = true;
        List<Long> doneItemIds = new ArrayList<>();
        for(ItemVo item: items){
            if(item.getStatus() != Global.WareConstant.PurchasingItem.FINISHED.getCode()){
                done = false;
            }else {
                doneItemIds.add(item.getItemId());
            }
        }
        //2.批量更新 采购项状态
        purchaseDetailDao.batchUpdateStatus(doneItemIds);
        //3.如果采购项全部完成，更新采购单状态
        if(done){
            purchaseDao.updateStatusById(purchaseVo.getId());
        }
       //4.根据已完成的采购项 更新库存
        // 4.1 批量拿到purchaseDetailEntities
        List<PurchaseDetailEntity> donePurchaseDetailEntities = purchaseDetailDao.selectBatchIds(doneItemIds);
        // 4.2 更新库存量
        donePurchaseDetailEntities.forEach(purchaseDetailEntity -> {
            QueryWrapper<WareSkuEntity> wrapper = new QueryWrapper<>();
            int count = wareSkuDao.selectCount(wrapper.eq("sku_id", purchaseDetailEntity.getSkuId()).
                    eq("ware_id", purchaseDetailEntity.getWareId()));
            //如果库存没有 货，需要新增
            if(count == 0){
                WareSkuEntity wareSkuEntity = new WareSkuEntity();
                wareSkuEntity.setSkuId(purchaseDetailEntity.getSkuId());
                wareSkuEntity.setWareId(purchaseDetailEntity.getWareId());//仓库ID
                //如果拿skuName出了异常，不做处理，程序继续往下走，避免事务回滚
                try {
                    R r = gatewayFeignService.info(wareSkuEntity.getSkuId());
                    if(r != null && r.getCode() == 0){
                        SkuInfoVo skuInfoVo = (SkuInfoVo) r.get("skuInfo");
                        wareSkuEntity.setSkuName(skuInfoVo.getSkuName());
                    }
                }catch (Exception e){

                }
                wareSkuEntity.setStock(purchaseDetailEntity.getSkuNum());
                wareSkuDao.insert(wareSkuEntity);
            }else{
                Long skuId = purchaseDetailEntity.getSkuId();
                Long wareId = purchaseDetailEntity.getWareId();
                Integer num = purchaseDetailEntity.getSkuNum();
                wareSkuDao.updateEntity(skuId, wareId, num);
            }
        });
    }


}